function flatten(arr) {
  const stack = [...arr]
  const result = []
  while (stack.length) {
    const item = stack.pop()
    if (Array.isArray(item)) {
      stack.push(...item)
    } else {
      result.unshift(item)
    }
  }
  return result
}

// 测试用例
console.log(flatten([1, [2, [3, 4, [6, 7, 8]], 5]])); // 应该输出 [1, 2, 3, 4, 5]